﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Secondary_File_System.lib;

namespace Secondary_File_System.Model
{
    class Inode
    {
        //Configuration
        public const int updatedTimeBytesLimit = 30;
        public const int fileNameBytesLimit = 100;

        //Properties
        public int index { get; set; }
        public DateTime updatedTime { get; set; }
        public bool readOnly { get; set; }
        public int firstBlockIndex { get; set; }
        public string fileName { get; set; }
        public int fileLength { get; set; } //单位：B，blockCount可以通过fileLength / K来计算
        public string showUpdatedTime()
        {
            return updatedTime.ToString("yyyy-MM-dd HH:mm:ss");
        }
        public static Inode readFromStream(ref FileStream fs)
        {
            Inode inode = new Inode();
            inode.index = Utility.readIntFromStream(ref fs);
            string updatedTimeString = Utility.readStringFromStream(ref fs, updatedTimeBytesLimit);
            inode.updatedTime = DateTime.Parse(updatedTimeString);
            inode.readOnly = Utility.readBoolFromStream(ref fs);
            inode.firstBlockIndex = Utility.readIntFromStream(ref fs);
            inode.fileName = Utility.readStringFromStream(ref fs, fileNameBytesLimit);
            inode.fileLength = Utility.readIntFromStream(ref fs);
            return inode;
        }
        public void save(ref FileStream fs)
        {
            byte[] tmpBuffer;
            //index
            Utility.writeBytesToStream(BitConverter.GetBytes(this.index), ref fs);
            //updatedTime
            byte[] bufferUpdatedTime = FileSystem.systemEncoding.GetBytes(this.showUpdatedTime());
            Utility.writeBytesToStream(bufferUpdatedTime, ref fs);
            tmpBuffer = new byte[updatedTimeBytesLimit - bufferUpdatedTime.Length];
            for (int i = 0; i < tmpBuffer.Length; i++) tmpBuffer[i] = (byte)' ';
            Utility.writeBytesToStream(tmpBuffer, ref fs);
            //readOnly
            Utility.writeBytesToStream(BitConverter.GetBytes(this.readOnly), ref fs);
            //firstBlockIndex
            Utility.writeBytesToStream(BitConverter.GetBytes(this.firstBlockIndex), ref fs);
            //fileName
            byte[] bufferFileName = FileSystem.systemEncoding.GetBytes(this.fileName);
            Utility.writeBytesToStream(bufferFileName, ref fs);
            tmpBuffer = new byte[fileNameBytesLimit - bufferFileName.Length];
            for (int i = 0; i < tmpBuffer.Length; i++) tmpBuffer[i] = (byte)' ';
            Utility.writeBytesToStream(tmpBuffer, ref fs);
            //fileLength
            Utility.writeBytesToStream(BitConverter.GetBytes(this.fileLength), ref fs);
        }
    }
}